﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using PH.Model.Commons;
namespace PH.Data.Commons
{
    public class FileCommand
    {
        public static void CreateNewFile(FileModel file)
        {
            if (file != null)
            {
                using (DBCentre db = new DBCentre())
                {
                    var dFile = Convertor.ConvertFrom<File, FileModel>(file);
                    db.DataContext.Files.Add(dFile);
                    db.DataContext.SaveChanges();
                }
            }
        }

        public static FileModel GetFile(Guid guid,bool noData=false)
        {
            if (guid != Guid.Empty)
            {
                using (DBCentre db = new DBCentre())
                {
                    var dFile = db.DataContext.Files.FirstOrDefault(p => p.Guid == guid);
                    if (dFile != null)
                    {
                        var file = Convertor.ConvertTo<FileModel, File>(dFile);
                        if (noData)
                            file.Data = null;
                        return file;
                    }
                }
            }
            return null;
        }

        public static FileModel GetFileProgressing(Guid guid)
        {
            if (guid != Guid.Empty)
            {
                using (DBCentre db = new DBCentre())
                {
                    var data = db.DataContext.Files.Where(p => p.Guid == guid).Select(p => new { p.Rows, p.NowRow }).FirstOrDefault();
                    if (data != null)
                        return new FileModel() { Rows = data.Rows, NowRow = data.NowRow };
                }
            }
            return null;
        }

        public static void UpdateFile(Guid guid, int now, int rows = 0)
        {
            using (DBCentre db = new DBCentre())
            {
                db.DataContext.UpdateFile(guid, now, rows);
                //var file = db.DataContext.Files.FirstOrDefault(p => p.Guid == guid);
                //if (file != null)
                //{
                //    if (rows > 0)
                //        file.Rows = rows;
                //    file.NowRow = now;
                //    db.DataContext.SaveChanges();
                //}
            }
        }
    }
}
